package array.generateMatrix;

/**
 * @ClassName SpiralOrder2
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-14 19:48
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class SpiralOrder2 {
    /**
     * 剑指 Offer 29. 顺时针打印矩阵
     * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
     * <p>
     * <p>
     * <p>
     * 示例 1：
     * <p>
     * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     * 输出：[1,2,3,6,9,8,7,4,5]
     * 示例 2：
     * <p>
     * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
     * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
     */
    public int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        if (row == 0) {
            return new int[0];
        }
        int[] resultArr = new int[matrix.length * matrix[0].length];
        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
        int start = 1;
        int end = matrix.length * matrix[0].length;
        int index = 0;
        while (index < end) {
            if (top <= bottom) {
                for (int i = left; i <= right; i++) {
                    resultArr[index++] = matrix[top][i];
                }
                top++;
            }

            if (left <= right) {
                for (int i = top; i <= bottom; i++) {
                    resultArr[index++] = matrix[i][right];
                }
                right--;
            }

            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    resultArr[index++] = matrix[bottom][i];
                }
                bottom--;
            }

            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    resultArr[index++] = matrix[i][left];
                }
                left++;
            }
        }
        return resultArr;
    }

    public static void main(String[] args) {
        SpiralOrder2 spiralOrder2 = new SpiralOrder2();
        int[] ints = spiralOrder2.spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}});
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }
    }
}